Next | Prev | Up | Top | Contents | Index
Concepts and Use of mmap()
The purpose of the mmap() system function (see the mmap(2) reference page) is to make the contents of a file directly accessible as part of the virtual address space of the user process. The results depend on the kind of file that is mapped:
- When the mapped object is a normal file, the process can load and store data from the file as if it were an array in memory.
- When the mapped object is a character device special file, the process can load and store data from device registers as if they were memory variables.
- When the mapped object is a block of memory owned and prepared by a pseudo-device driver, the process gains access to some special piece of memory data that it would not normally be able to access.
In all cases, access is gained through normal load and store instructions, without the overhead of calling system functions such as read(). Furthermore, the same mapping can be executed by other processes, in which case the same memory, or file, or device is shared by multiple, concurrent processes. This is how shared memory segments are achieved.
Use of mmap()
The mmap() system function takes four key parameters:
- the file descriptor for an open file, which can be either a normal disk file or a device special file
- an offset within that file at which the mapped data is to start. For a normal file, this is a file offset; for a device file, it represents an address in the address space of the device or the bus
- the length of data to be mapped
- protection flags, showing whether the mapped data is read-only or read-write
When the mapped object is a normal file, the filesystem implements the mapping. The filesystem does not call the block device driver for assistance in mapping a file. It does call the block device driver pfxstrategy() entry to read and write blocks of file data as necessary, but the mapping of pages of data into pages of memory is controlled in the filesystem code.
When the mapped object is a device special file, the mmap() parameters are passed to the device driver at either its pfxmmap() or pfxmap() entry point. The device driver interprets the parameters in the context of the device, and uses a kernel function to create the mapping.
Persistent Mappings
Once a device or kernel memory has been mapped into some user address space, the mapping persists until the user process terminates or calls unmap() (see the unmap(2) reference page). In particular, the mapping does not end simply because the device special file is closed. You cannot assume, in the pfxclose() or pfxunload() entry points, that all mappings to devices have ended.
Next | Prev | Up | Top | Contents | Index